package tool

import "strconv"

// 获取Json里面的某一值，嵌套层层深入

// JSONGetValue 参数jobj是HoMap或HoList类形对象,
//   参数keys是索引数组，类型是int或string（HoMap用string，HoList对应int）
func JSONGetValue(jobj interface{}, keys ...interface{}) (ret interface{}) {
	var keystr string
	var keyint int
	var ok bool
	var jMap map[string]interface{}
	var jList []interface{}

	ret = nil
	for _, key0 := range keys {
		if keystr, ok = key0.(string); ok {
			if jMap, ok = jobj.(map[string]interface{}); !ok {
				var homp HoMap
				if homp, ok = jobj.(HoMap); ok { // 重定义的map
					jMap = map[string]interface{}(homp)
				} else if jList, ok = jobj.([]interface{}); ok  { // array
					tmpKey, err := strconv.Atoi(keystr) // array的索引必须是数字
					if nil == err && len(jList) > tmpKey {
						ret = jList[tmpKey]
						jobj = ret
						continue
					}
					return nil
				} else {
					return nil
				}
			}
			ret = jMap[keystr]
			jobj = ret
		} else if keyint, ok = key0.(int); ok {
			if jList, ok = jobj.([]interface{}); !ok {
				var olist HoList
				if olist, ok = jobj.(HoList); !ok {
					return nil
				}
				jList = []interface{}(olist)
			}

			if len(jList) > keyint {
				ret = jList[keyint]
				jobj = ret
			} else {
				return nil
			}

		}

		if nil == jobj {
			break
		}
	}

	return ret
}

// JSONGetString 返回字符串型式
func JSONGetString(jobj interface{}, keys ...interface{}) (string, bool) {
	ret := JSONGetValue(jobj, keys...)
	return Conver2String(ret)
}

// JSONGetInt 返回字符串型式
func JSONGetInt(jobj interface{}, keys ...interface{}) (int, bool) {
	ret := JSONGetValue(jobj, keys...)
	return Conver2Int(ret)
}

// JSONGetFloat64 返回字符串型式
func JSONGetFloat64(jobj interface{}, keys ...interface{}) (float64, bool) {
	ret := JSONGetValue(jobj, keys...)
	return Conver2Float64(ret)
}
